<template>
  <div>
    <el-form>
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="formData.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="formData.tmId">
          <el-option
            v-for="opt in tradeMarkOption"
            :key="opt.id"
            :label="opt.tmName"
            :value="opt.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          placeholder="SPU描述"
          type="textarea"
          :rows="3"
          v-model="formData.description"
        ></el-input>
      </el-form-item>
      <!-- :show-file-list="false" -->
      <el-form-item>
        <el-upload
          class="uploader"
          :action="uploadAction"
          :on-success="uploadSuccess"
          list-type="picture-card"
          :on-preview="uploadPreview"
          :on-remove="removePreview"
          :before-upload="beforeUpload"
          :file-list="fileList"
          ><el-icon class="uploader-icon"><ele-Plus></ele-Plus></el-icon
        ></el-upload>
        <el-button @click="printmy">打印数据</el-button>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="selectedBaseSaleAttr"
          :placeholder="`还有${attBaseNotUsed.length}个`"
          :disabled="attBaseNotUsed.length === 0"
        >
          <div style="margin-bottom: 20px">
            <el-option
              v-for="opt in attBaseNotUsed"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id + '|' + opt.name"
            ></el-option>
          </div>
        </el-select>
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="addSaleAttrItem"
          :disabled="attBaseNotUsed.length === 0"
          >添加销售属性</el-button
        >
        <el-table border stripe :data="formData.spuSaleAttrList">
          <el-table-column
            :width="80"
            label="序号"
            type="index"
          ></el-table-column>
          <el-table-column
            :width="150"
            label="属性名"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性名列表">
            <template #="{ row }">
              <el-tag
                v-for="(item, index) in row.spuSaleAttrValueList"
                :key="item.baseSaleAttrId"
                closable
                @close="closeAttrTag(row.spuSaleAttrValueList, index)"
                >{{ item.saleAttrValueName }}</el-tag
              >
              <el-input
                style="width: 50px"
                v-if="row.isEidt"
                ref="addSaleAttrIpt"
                v-model="inputSaleAttrValue"
                @keydown.enter="lostAndEnterhAttrItem(row)"
                @blur="lostAndEnterhAttrItem(row)"
              >
              </el-input>
              <el-button type="primary" v-else @click="isAddSaleAttrItem(row)"
                >添加属性值</el-button
              >
            </template>
          </el-table-column>
          <el-table-column :width="150" label="操作">
            <template #="{ row }">
              <el-button
                icon="ele-Delete"
                type="danger"
                @click="delSaleAttrItem(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpuHandler">保存</el-button>
        <el-button @click="cancelSpuHandler">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog v-model="showPreview" width="80%" :title="previewDialog.name">
      <img :src="previewDialog.imgUrl" style="width: 80%" alt="" />
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onBeforeUnmount } from "vue";
export default defineComponent({
  name: "SpuForm",
});
</script>
<script setup lang="ts">
import { reqBaseAttr } from "@/api/attr";
import type { BaseAttrType } from "@/api/attr";
import { reqTrademarkList } from "@/api/trademark";
import type { trademarkListType } from "@/api/trademark";
import type {
  SaveSpuInfoType,
  spuSaleAttrListType,
  spuSaleAttrValueListType,
  recordsType,
} from "@/api/spu";
import * as api from "@/api/spu";
import { ElMessage, ElMessageBox } from "element-plus";
import VIEW_TYPE from "../../viewType";
import { ref, computed, nextTick } from "vue";
import type { UploadFile, UploadRawFile, UploadUserFile } from "element-plus";
//引入商店
import getCategoryStore from "@/stores/category";
import { storeToRefs } from "pinia";
//添加引入图片
const props = defineProps<{ data?: recordsType }>();
// console.log("props", props.data);

const emit = defineEmits(["change-view"]);
//初始化ref pinia
const categoryStore = getCategoryStore();
const { category3Id } = storeToRefs(categoryStore);
//上传地址
const uploadAction = `${import.meta.env.VITE_API_URL}/product/upload`;
//0、ref数据区域
//获取ipt组件实例
const addSaleAttrIpt = ref();
//0-1表单数据-品牌列表
const tradeMarkOption = ref<trademarkListType[]>([]);
//编写新的ts
type newSpuSaleAttrListType = spuSaleAttrListType & { isEidt?: boolean };

type newSaveSpuInfoType = Omit<SaveSpuInfoType, "spuSaleAttrList"> & {
  spuSaleAttrList: newSpuSaleAttrListType[];
};

//0-2传入参数初始化
const formData = ref<newSaveSpuInfoType>({
  category3Id: category3Id.value as number,
  description: "",
  spuImageList: [],
  spuName: "",
  spuSaleAttrList: [],
  tmId: 1,
});
if (props.data) {
  formData.value.id = props.data.id;
  formData.value.category3Id = props.data.category3Id;
  formData.value.description = props.data.description;
  formData.value.spuName = props.data.spuName;
  formData.value.tmId = props.data.tmId;
  getImageList(props.data.id);
  getAttrValueList(props.data.id);
}
//0-3预览图片dialog是否显示
const showPreview = ref<boolean>(false);
//0-4预览图片信息
const previewDialog = ref<{
  name: string;
  imgUrl: string;
}>({
  name: "",
  imgUrl: "",
});
//0-5获取初始化attr数据
const baseAttrList = ref<BaseAttrType[]>([]);
//0-6已选择基础数据
const selectedBaseSaleAttr = ref("");
//0-7添加单个attr属性
const inputSaleAttrValue = ref("");
// 0-8图片上传列表
const fileList = ref<UploadUserFile[]>();
1; // 1、初始化

//取消按钮
const cancelSpuHandler = () => {
  formData.value = {
    category3Id: category3Id.value as number,
    description: "",
    spuImageList: [],
    spuName: "",
    spuSaleAttrList: [],
    tmId: 1,
  };

  emit("change-view", VIEW_TYPE.LIST);
};
//2、表单数据
//1、品牌列表的初始化
const getTradeMarkList = async () => {
  try {
    tradeMarkOption.value = await reqTrademarkList();

    // console.log("result", result);
  } catch (e) {
    ElMessage.error("获取列表失败");
  }
};

getTradeMarkList();
//2、上传图片
//上传图片校验
const beforeUpload = (rawFile: UploadRawFile) => {
  // try {
  //   // const isRepeat = formData.value.spuImageList.reduce((p: any, c: any) => {
  //   //   c.imgName === rawFile.name ? p + 1 : p;
  //   //   return p > 2 ? true : false;
  //   // }, 0);
  //   //寻找预览图会出错 可以自己重写
  //   const isRepeat = formData.value.spuImageList.find(
  //     (item) => item.imgName === rawFile.name
  //   );
  //   console.log(isRepeat);
  //   if (isRepeat) {
  //     ElMessage.error("图片名重复");
  //     return false;
  //   }
  // } catch (e) {}
};
const uploadSuccess = (response: { data: string }, uploadFile: UploadFile) => {
  console.log("上传图片", "A");
  // console.log(response);
  // console.log(uploadFile.url);

  try {
    formData.value.spuImageList.push({
      imgName: uploadFile.name,
      imgUrl: response.data,
    });
  } catch (e) {}
};
//3、图片预览
const uploadPreview = (UploadFile: UploadFile) => {
  // console.log("UploadFile", UploadFile);
  if (UploadFile.response as { data: string }) {
    previewDialog.value = {
      name: UploadFile.name,
      imgUrl: (UploadFile.response as { data: string })!.data,
    };

    showPreview.value = true;
  } else {
    previewDialog.value = {
      name: UploadFile.name,
      imgUrl: UploadFile.url as string,
    };

    showPreview.value = true;
  }
};
//4、删除预览图事件
const removePreview = (UploadFile: UploadFile) => {
  if (UploadFile.response as { data: string }) {
    formData.value.spuImageList = formData.value.spuImageList.filter((item) => {
      return item.imgUrl !== (UploadFile.response as { data: string }).data;
    });
  }
};
//打印工具
const printmy = () => {
  console.log("formData", formData.value.spuImageList);
};
//5、获取基础属性
const getBaseAttr = async () => {
  try {
    baseAttrList.value = await reqBaseAttr();
  } catch (e) {
    ElMessage.error("获取初始化数据失败");
  }
};

//6-判断是否已使用
const attBaseNotUsed = computed(() =>
  baseAttrList.value.reduce(
    (p: BaseAttrType[], c: BaseAttrType): BaseAttrType[] => {
      formData.value.spuSaleAttrList.find(
        (item) => c.id === item.baseSaleAttrId
      )
        ? p
        : p.push(c);
      return p;
    },
    []
  )
);
//7-将选中数据添加formData
// console.log("attBaseNotUsed", attBaseNotUsed);
const addSaleAttrItem = () => {
  if (selectedBaseSaleAttr.value === "") {
    ElMessage.error("请选择属性");
  } else {
    const [id, name] = selectedBaseSaleAttr.value.split("|");
    formData.value.spuSaleAttrList.push({
      baseSaleAttrId: Number(id),
      saleAttrName: name,
      spuSaleAttrValueList: [],
      isEidt: false,
    });
  }
  selectedBaseSaleAttr.value = "";
};
//8-删除attr属性
const delSaleAttrItem = async (row: newSpuSaleAttrListType) => {
  try {
    await ElMessageBox.confirm("是否删除", "提示");

    formData.value.spuSaleAttrList = formData.value.spuSaleAttrList.filter(
      (item) => item !== row
    );
  } catch (e) {}
};
getBaseAttr();
//9-点击添加按钮
const isAddSaleAttrItem = (row: newSpuSaleAttrListType) => {
  row.isEidt = true;
  nextTick(() => {
    addSaleAttrIpt.value.focus();
  });
};
//10-回车失去焦点
const lostAndEnterhAttrItem = (row: newSpuSaleAttrListType) => {
  if (!row.isEidt) return;
  if (inputSaleAttrValue.value !== "") {
    //去重
    const repeat = row.spuSaleAttrValueList.find(
      (item) => item.saleAttrValueName === inputSaleAttrValue.value
    );
    if (repeat) {
      inputSaleAttrValue.value = "";
      ElMessage.error("重复");
      nextTick(() => {
        addSaleAttrIpt.value.focus();
      });
      return;
    }
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrName: row.saleAttrName,
      saleAttrValueName: inputSaleAttrValue.value,
    });
    inputSaleAttrValue.value = "";
    // console.log(repeat);
  }
  console.log("11111");

  row.isEidt = false;
};
//11-关闭tag
const closeAttrTag = (arr: spuSaleAttrValueListType[], index: number) => {
  arr.splice(index, 1);
};
//12-保存按钮
const saveSpuHandler = async () => {
  formData.value.spuSaleAttrList.forEach((item) => {
    delete item.isEidt;
  });
  try {
    // if (formData.value.id) {
    //   await api.reqChangeSpuInfo(formData.value);
    // } else {
    //   await api.reqSaveSpuInfo(formData.value);
    // }
    await api.reqSaveSpuInfo(formData.value);
    cancelSpuHandler();
    ElMessage.success("添加成功");
  } catch (e) {
    ElMessage.error("添加失败");
  }
};
// 13-获取图片
async function getImageList(id: number) {
  try {
    formData.value.spuImageList = await api.reqSpuImgList(id);
    fileList.value = formData.value.spuImageList.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      };
    });
  } catch (e) {
    ElMessage.error("获取图片列表失败");
  }
}

//14-获取销售属性
async function getAttrValueList(id: number) {
  try {
    formData.value.spuSaleAttrList = await api.reqSpuSaleAttrList(id);
  } catch (e) {
    ElMessage.error("获取销售属性失败");
  }
}
</script>
<style scoped>
.uploader .thumb {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
